package com.csjbot.weedle_auto.fragment.manual

import android.content.Context
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import butterknife.bindView
import com.csjbot.weedle_auto.R
import com.csjbot.weedle_auto.SerialServer.util.bean.SerialPortEvents
import com.csjbot.weedle_auto.SerialServer.util.bean.SerialPortExceptionListener
import com.csjbot.weedle_auto.adapter.FragmentListener
import com.csjbot.weedle_auto.app.BaseApplication
import com.csjbot.weedle_auto.file.constants_util.Constants
import com.csjbot.weedle_auto.fragment.BaseFramgent
import com.csjbot.weedle_auto.fragment.bean.AdioCheckBean
import com.csjbot.weedle_auto.serialport_util.SerialPortUtil
import com.csjbot.weedle_auto.util.Csjlogger
import com.csjbot.weedle_auto.util.TimeUtil
import com.google.common.base.Preconditions.checkNotNull
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.IOException
import java.security.InvalidParameterException

/**
 * Created by chenqi on 8/4/17.
 */

class ManualFragment : BaseFramgent(), SerialPortExceptionListener, ManualContract.view {
    val clear: Button by bindView(R.id.clear)


    val other: Button by bindView(R.id.other)
    val scrTitle: TextView by bindView(R.id.scr_title)

    val scrText: TextView by bindView(R.id.scr_text)

    val scrRadio1: RadioButton by bindView(R.id.scr_radio1)

    val scrRadio2: RadioButton by bindView(R.id.scr_radio2)
    val scrGroup: RadioGroup by bindView(R.id.scr_group)

    val inrTitle: TextView by bindView(R.id.inr_title)
    val inrText: TextView by bindView(R.id.inr_text)
    val inrRadio1: RadioButton by bindView(R.id.inr_radio1)

    val inrRadio2: RadioButton by bindView(R.id.inr_radio2)

    val inrGroup: RadioGroup by bindView(R.id.inr_group)

    val plateInrTitle: TextView by bindView(R.id.plate_inr_title)

    val plateInrText: TextView by bindView(R.id.plate_inr_text)

    val plateInrRadio1: RadioButton by bindView(R.id.plate_inr_radio1)

    val plateInrRadio2: RadioButton by bindView(R.id.plate_inr_radio2)

    val plateInrGroup: RadioGroup by bindView(R.id.plate_inr_group)

    val oaTitle: TextView by bindView(R.id.oa_title)

    val oaText: TextView by bindView(R.id.oa_text)

    val oaRadio1: RadioButton by bindView(R.id.oa_radio1)

    val oaRadio2: RadioButton by bindView(R.id.oa_radio2)
    val oaGroup: RadioGroup by bindView(R.id.oa_group)

    val touch: Button by bindView(R.id.touch)

    val touchText: TextView by bindView(R.id.touch_text)

    val touchRadio1: RadioButton by bindView(R.id.touch_radio1)

    val touchRadio2: RadioButton by bindView(R.id.touch_radio2)

    val touchGroup: RadioGroup by bindView(R.id.touch_group)

    val sn: Button by bindView(R.id.sn)

    val snUpTitle: TextView by bindView(R.id.sn_up_title)

    val snUpText: TextView by bindView(R.id.sn_up_text)

    val snDownRadio1: RadioButton by bindView(R.id.sn_down_radio1)

    val snDownRadio2: RadioButton by bindView(R.id.sn_down_radio2)

    val snDownGroup: RadioGroup by bindView(R.id.sn_down_group)

    val snDownTitle: TextView by bindView(R.id.sn_down_title)

    val snDownText: TextView by bindView(R.id.sn_down_text)

    val snUpRadio1: RadioButton by bindView(R.id.sn_up_radio1)

    val snUpRadio2: RadioButton by bindView(R.id.sn_up_radio2)

    val snUpGroup: RadioGroup by bindView(R.id.sn_up_group)


    private val TAG = "ManualFragment"
    private val append = "\r\n"
    private lateinit var listener: FragmentListener
    private lateinit var adioCheckBean: AdioCheckBean
    private lateinit var presenter: ManualContract.presenter

    override val resureID: Int
        get() = R.layout.manual_framgent

    override fun initView(view: View) {
        SerialPortUtil.setSerialPortExceptionListener(this)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        adioCheckBean = BaseFramgent.sharePreferenceTools.getModel(Constants.CHECKINFOR, AdioCheckBean::class.java)!!
        setMovementMethodToText()
        initPL()
        initViewDpi()
    }

    private fun initViewDpi() {
        val dm = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(dm)
        val heightPixels = dm.heightPixels
        val texth = (heightPixels * 0.14).toInt()
        scrText.height = texth
        inrText.height = texth
        plateInrText.height = texth
        touchText.height = texth
        oaText.height = texth
        snUpText.height = texth
        snDownText.height = texth
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    //
    private fun initPL() {
        snUpGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.sn_up_radio1 -> adioCheckBean.isSn_up = true
                R.id.sn_up_radio2 -> adioCheckBean.isSn_up = false
                else -> {
                }
            }
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            listener.onFragmentClickListener(1)

        }
        //分清楚
        snDownGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.sn_down_radio1 -> adioCheckBean.isSn_down = true
                R.id.sn_down_radio2 -> adioCheckBean.isSn_down = true
                else -> {
                }
            }
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            listener.onFragmentClickListener(1)
        }
        //分清楚
        touchGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.touch_radio1 -> adioCheckBean.isTouch = true
                R.id.touch_radio2 -> adioCheckBean.isTouch = false
                else -> {
                }
            }
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            listener.onFragmentClickListener(1)
        }

        //分清楚
        oaGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.oa_radio1 -> adioCheckBean.isOa = true
                R.id.oa_radio2 -> adioCheckBean.isOa = false
                else -> {
                }
            }
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            listener.onFragmentClickListener(1)
        }

        //分清楚
        scrGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.scr_radio1 -> adioCheckBean.isScr = true
                R.id.scr_radio2 -> adioCheckBean.isScr = false
                else -> {
                }
            }
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            listener.onFragmentClickListener(1)
        }
        //分清楚
        inrGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.inr_radio1 -> {
                }
                R.id.inr_radio2 -> {
                }
                else -> {
                }
            }//                        adioCheckBean.setInr(true);
            //                        adioCheckBean.setInr(false);
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            listener.onFragmentClickListener(1)
        }

        //分清楚
        plateInrGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.plate_inr_radio1 -> {
                }
                R.id.plate_inr_radio2 -> {
                }
                else -> {
                }
            }//                        adioCheckBean.setPlate_inr(true);
            //                        adioCheckBean.setPlate_inr(false);
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            listener.onFragmentClickListener(1)

        }
    }

    /**
     * 添加一个
     *
     * @param evet 2017年4月12日 添加了充电显示的功能
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnEventMainThread(evet: SerialPortEvents) {
        Csjlogger.info("chenqi ManualFragment{}")
        presenter.setSerialPortInforMation(evet)
    }

    override fun snUp(msg: String) {
        activity.runOnUiThread {
            snUpText.append(TimeUtil.currenTime + append)
            snUpText.append(getString(R.string.top_sn) + msg + append)
            adioCheckBean.sn_up_text = msg
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            val offset = snUpText.lineCount * snUpText.lineHeight
            if (offset > snUpText.height) {
                snUpText.scrollTo(0, offset - snUpText.height)
            }
        }
    }

    override fun snDown(msg: String) {
        activity.runOnUiThread {
            snDownText.append(TimeUtil.currenTime + append)
            snDownText.append(getString(R.string.bottom_sn) + msg + append)
            adioCheckBean.sn_down_text = msg
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            val offset = snDownText.lineCount * snDownText.lineHeight
            if (offset > snDownText.height) {
                snDownText.scrollTo(0, offset - snDownText
                        .height)
            }
        }
    }


    /**
     * 给text添加滑动属性
     */
    private fun setMovementMethodToText() {
        scrText.movementMethod = ScrollingMovementMethod.getInstance()
        inrText.movementMethod = ScrollingMovementMethod.getInstance()
        plateInrText.movementMethod = ScrollingMovementMethod.getInstance()
        oaText.movementMethod = ScrollingMovementMethod.getInstance()
        touchText.movementMethod = ScrollingMovementMethod.getInstance()
        snUpText.movementMethod = ScrollingMovementMethod.getInstance()
        snDownText.movementMethod = ScrollingMovementMethod.getInstance()
    }


    /**
     * 清空scrText数据
     *
     * @param
     */
    private fun removeTextInformation() {
        activity.runOnUiThread {
            scrText.text = ""
            inrText.text = ""
            plateInrText.text = ""
            oaText.text = ""
            touchText.text = ""
            snUpText.text = ""
            snDownText.text = ""
        }
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.other -> {
                BaseApplication.instance.serial.putOtherOrder()
            }
            R.id.sn -> {
            }
            R.id.touch -> {
            }
            R.id.sn_down_title -> BaseApplication.instance.serial.putSnDown()
            R.id.sn_up_title -> BaseApplication.instance.serial.putSnUp()
            else -> {
            }
        }//一开始发送
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
    }

    override fun ioException(e: IOException) {
        removeTextInformation()
        Csjlogger.info("chenqi fragment", e)
    }

    override fun invalidException(e: InvalidParameterException) {
        removeTextInformation()
        Csjlogger.info("chenqi fragment", e)
    }

    override fun securityException(e: SecurityException) {
        removeTextInformation()
        Toast.makeText(activity, "串口连接失败！", 1000).show()
        Csjlogger.info("chenqi fragment", e)
    }

    override fun otherException(error: Boolean) {
        removeTextInformation()
        Csjlogger.info("chenqi fragment")
    }

    override fun onAttach(context: Context?) {
        try {
            listener = (context as FragmentListener?)!!
        } catch (e: Exception) {
            e.printStackTrace()
        }

        super.onAttach(context)
    }

    /**
     * 需要界面重新展示时调用这个方法
     */
    override fun onHiddenChanged(hidden: Boolean) {
        // TODO Auto-generated method stub
        super.onHiddenChanged(hidden)
        if (!hidden) {
            activity.runOnUiThread {
                scrText.append(TimeUtil.currenTime + append)
                inrText.append(TimeUtil.currenTime + append)
                plateInrText.append(TimeUtil.currenTime + append)
                oaText.append(TimeUtil.currenTime + append)
            }
        }
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // TODO: inflate a fragment view
        val rootView = super.onCreateView(inflater, container, savedInstanceState)
        ManualPresenter(this)
        presenter.start()
        return rootView
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun setPresenter(presenter: ManualContract.presenter) {
        this.presenter = checkNotNull(presenter)
    }

    override fun showSerialResults() {

    }

    override fun touch(msg: String) {
        activity.runOnUiThread {
            touchText.append(TimeUtil.currenTime + append)
            touchText.append("摸手串口数据为：" + msg + append)
            adioCheckBean.touch_text = msg
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)
            val offset = touchText.lineCount * touchText.lineHeight
            if (offset > touchText.height) {
                touchText.scrollTo(0, offset - touchText.height)
            }
        }
    }


    override fun other(scr: Int, inr: String, plate_inr: String, oa: Int) {
        activity.runOnUiThread {
            scrText.append(TimeUtil.currenTime + append)
            scrText.append(getString(R.string.scram_data) + scr + append)
            inrText.append(TimeUtil.currenTime + append)
            inrText.append(getString(R.string.Infrared_data) + inr + append)
            plateInrText.append(TimeUtil.currenTime + append)
            plateInrText.append(getString(R.string.Infrared_plate) + plate_inr + append)
            oaText.append(TimeUtil.currenTime + append)
            oaText.append(getString(R.string.ultrasonic) + oa + getString(R.string.centimeter) + append)

            adioCheckBean.scr_text = scr.toString()
            adioCheckBean.inr_text = inr
            adioCheckBean.plate_inr_text = plate_inr
            adioCheckBean.oa_text = oa.toString()
            BaseFramgent.sharePreferenceTools.putModel<AdioCheckBean>(Constants.CHECKINFOR, adioCheckBean)

            if (scrText.lineCount * scrText.lineHeight > scrText.height) {
                scrText.scrollTo(0,
                        scrText.lineCount * scrText.lineHeight - scrText.height)
            }

            if (inrText.lineCount * inrText.lineHeight > inrText.height) {
                inrText.scrollTo(0,
                        inrText.lineCount * inrText.lineHeight - inrText.height)
            }

            if (plateInrText.lineCount * plateInrText.lineHeight > plateInrText.height) {
                plateInrText.scrollTo(0,
                        plateInrText.lineCount * plateInrText.lineHeight - plateInrText.height)
            }

            if (oaText.lineCount * oaText.lineHeight > oaText.height) {
                oaText.scrollTo(0,
                        oaText.lineCount * oaText.lineHeight - oaText.height)
            }
        }
    }

    override fun showTestResults(scr: String, inr: String, plate: String, oa: String, tuch: String, snUp: String, snDown: String) {
    }

}
